<template>
  <div class="list-page-b">
    <div class="list-page">
      <div class="list-search">
        <div class="singe-search">
          <el-input v-model="searchForm.roleName" clearable :size="size" placeholder="请输入角色名称"></el-input>
        </div>
        <div class="singe-search-btn">
          <el-button class="singe-search-btn1" @click="getList(1)">查询</el-button>
          <el-button class="singe-search-btn2" @click="resetForm">重置</el-button>
        </div>
        <div class="singe-search-btn saveBtn">
          <el-button class="singe-search-btn1" @click="add">新增</el-button>
          <el-button class="singe-search-btn2" @click="setting">权限配置</el-button>
        </div>
      </div>
      <div class="table-main">
        <el-table :data="tableData" style="width: 100%" :height="tableHeight" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" label="序号" width="70" align="center">
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称" min-width="150" align="center">
          </el-table-column>
          <el-table-column prop="roleAlias" label="角色编码" min-width="150" align="center">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="150" align="center">
          </el-table-column>
          <el-table-column label="操作" min-width="120" align="center">
            <template slot-scope="scope" v-if="scope.row.roleName != '普通警员' && scope.row.roleName != '平台管理员' && scope.row.roleName != '超级管理员' ">
              <el-button type="text" :size="size" @click="update(scope.row)" style="color:#2E488B;">编辑</el-button>
              <el-button type="text" :size="size" @click="rowDelete(scope.row)" style="color:#FF4329;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" class="form-dialog" append-to-body
        :close-on-click-modal="false">
        <div class="modalBody body-have-footer" v-if="dialogVisible">
          <el-form ref="DialogForm" :model="dialogForm" :rules="rules" label-position="top">
            <el-form-item label="角色名称: (最多20字符)" prop="roleName">
              <template slot="label">
                <span class="label-text">角色名称:</span>
                <span class="label-subtext">(最多20字符)</span>
              </template>
              <el-input v-model="dialogForm.roleName" :maxlength="10" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item label="角色名称: (最多20字符)" prop="roleAlias">
              <template slot="label">
                <span class="label-text">角色编码:</span>
              </template>
              <el-input v-model="dialogForm.roleAlias" placeholder="请输入角色编码"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div style="clear: both"></div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false" size="small">
            取 消
          </el-button>
          <el-button type="primary" @click="submitDialog('DialogForm')" size="small">
            提 交
          </el-button>
        </span>
      </el-dialog>

      <el-dialog title="权限配置" :visible.sync="settingDialogVisible" width="500px" class="form-dialog" append-to-body
        :close-on-click-modal="false">
        <div class="modalBody body-have-footer" v-if="settingDialogVisible">
          <el-tree :data="data" show-checkbox node-key="id" ref="treeMenu" :default-checked-keys="menuTreeObj"
            @node-click="handleNodeClick" highlight-current @check-change="checkAll">
          </el-tree>
        </div>
        <div style="clear: both"></div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="settingDialogVisible=false" size="small">
            取 消
          </el-button>
          <el-button type="primary" @click="submitSettingDialog()" size="small">
            提 交
          </el-button>

        </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import {
    getList,
    remove,
    submit,
    getTree,
    grant,
    getTreeKey
  } from '../../../api/famfrontend/roleManagement/roleManagement';
  export default {
    data() {
      var checkSort = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请填写角色排序'));
        } else {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            callback();

          }
        }
      };
      return {
        size: "small",
        dialogTitle: "",
        searchForm: {
          roleName: '',
          roleAlias: '',
        },
        dialogVisible: false,
        settingDialogVisible: false,
        data: [],
        tableData: [],
        multipleSelection: [],
        menuTreeObj: [],
        dialogForm: {
          id: '',
          roleName: '',
          roleAlias: '',
          sort: '',
        },
        rules: {
          roleName: [{
            required: true,
            message: '请填写角色名称',
            trigger: 'blur'
          }],
          roleAlias: [{
            required: true,
            message: '请填写角色编码',
            trigger: 'blur'
          }],
        },
        selectedNodeKey: null
      }
    },
    created() {
      this.getList()
    },
    computed: {
      tableHeight() {
        let h = document.body.clientHeight - 244;
        return h;
      },
    },
    methods: {
      //分页
      getList() {
        const params = {
          roleName: this.searchForm.roleName,
          roleAlias: this.searchForm.roleAlias,
        }
        getList(params).then(res => {
          this.tableData = res.data.data
        })
      },
      //清空
      resetForm() {
        this.searchForm.roleName = '';
        this.searchForm.roleAlias = '';
        this.getList()
      },
      //提交新增信息
      submit() {
        const params = {
          id: this.dialogForm.id,
          roleName: this.dialogForm.roleName,
          roleAlias: this.dialogForm.roleAlias,
          sort: this.dialogForm.sort,
        }
        submit(params).then(res => {
          if (res.data.code == '200') {
            this.dialogVisible = false;
            if (this.dialogForm.id) {
              this.$message.success('编辑成功');
            } else {
              this.$message.success('新增成功');
            }
            this.getList();
          }
        })
      },
      //新增
      add() {
        this.dialogForm.id = '';
        this.dialogForm.roleName = '';
        this.dialogForm.roleAlias = '';
        this.dialogForm.sort = '';
        this.dialogTitle = '新增角色';
        if (this.$refs.DialogForm) {
          this.$refs.DialogForm.resetFields();
        }
        this.dialogVisible = true;
      },
      //编辑
      update(row) {
        this.dialogTitle = '编辑角色';
        this.dialogForm = JSON.parse(JSON.stringify(row));
        this.dialogVisible = true;
      },
      submitDialog(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submit();
          }
        });
      },
      submitSettingDialog() {
        const menuList = this.$refs.treeMenu.getCheckedKeys();
        let ids = [];
        this.multipleSelection.forEach(ele => {
          ids.push(ele.id);
        });
        const params = {
          menuIds: menuList,
          roleIds: ids,
          apiScopeIds: [],
          dataScopeIds: [],
        }
        grant(params).then(res => {
          if (res.data.code == '200') {
            this.settingDialogVisible = false;
            this.$message.success('权限设置成功');
          }
        })
      },
      //删除
      rowDelete(row) {
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          remove(row.id).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          })
        }).catch(() => {});
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      setting() {
        if (this.multipleSelection.length !== 1) {
          this.$message.warning("只能选择一条数据");
          return;
        }
        this.menuTreeObj = [];
        let ids = [];
        this.multipleSelection.forEach(ele => {
          ids.push(ele.id);
        });
        this.settingDialogVisible = true;
        getTree().then(res => {
          if (res.data.code == '200') {
            let superSet = {
              id: 0,
              label: "超级管理员（全部权限）"
            }
            this.data = res.data.data;
            this.data.unshift(superSet)
            console.log(this.data)
          }
        })
        getTreeKey(ids).then(res => {
          if (res.data.code == '200') {
            this.menuTreeObj = res.data.data.menu;
          }
        })

      },
      checkAll(data, checked, indeterminate) {
        console.log("data:", data)
        if (data.id == 0) {
          this.traverseAndCheck(this.data, checked)
          this.updateCheckedState();
        }
      },
      handleNodeClick(node) {
        this.selectedNodeKey = node.id;
      },
      traverseAndCheck(nodes, checked) {
        if (nodes.length > 0) {
          nodes.forEach(node => {
            this.$set(node, 'checked', checked);
            if (node.children) {
              this.traverseAndCheck(node.children, checked);
            }
          });
        }
      },
      updateCheckedState() {
        const tree = this.$refs.treeMenu;
        if (tree) {
          const checkedKeys = this.getCheckedKeys();
          console.log("checkedKeys:", checkedKeys)
          tree.setCheckedKeys(checkedKeys);
        }
      },
      getCheckedKeys() {
        const checkedKeys = [];
        this.traverseCheckedNodes(this.data, checkedKeys);
        return checkedKeys;
      },
      traverseCheckedNodes(nodes, checkedKeys) {
        // if (nodes.length > 0) {
        nodes.forEach(node => {
          if (node.checked) {
            checkedKeys.push(node.id);
          }
          if (node.children) {
            this.traverseCheckedNodes(node.children, checkedKeys);
          }
        });
        // }

      }
    }
  }
</script>

<style scoped lang="scss">
  @import '../../../styles/page/list';

  .list-search {
    width: 100%;
    height: 86px;
    padding: 0px;
  }

  .singe-search {
    width: 296px !important;
    height: 36px !important;
    margin-right: 24px !important;

    ::v-deep .el-input input {
      width: 296px;
      height: 36px;
    }

    ::v-deep .el-select input {
      width: 296px;
      height: 36px;
    }

    ::v-deep .el-cascader input {
      width: 296px;
      height: 36px;
    }
  }

  .singe-search-btn {
    height: 36px !important;

    .singe-search-btn1 {
      width: 88px !important;
      height: 36px !important;
      background: #2E488B !important;
      box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
      border-radius: 4px 4px 4px 4px !important;
      opacity: 1 !important;
      padding: 0 !important;

      font-size: 14px !important;
      font-family: PingFang SC-Regular, PingFang SC !important;
      font-weight: 400 !important;
      color: #FFFFFF !important;
      margin-right: 0 !important;
    }

    .singe-search-btn2 {
      width: 88px !important;
      height: 36px !important;
      background: #FFFFFF !important;
      box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
      border-radius: 4px 4px 4px 4px !important;
      opacity: 1 !important;
      border: 1px solid #C1D3EE !important;
      padding: 0 !important;

      font-size: 14px !important;
      font-family: PingFang SC-Regular, PingFang SC !important;
      font-weight: 400 !important;
      color: #2E488B !important;
    }
  }

  .saveBtn {
    position: absolute;
    right: 0px;
  }

  .label-text {
    color: #333;
    /* 设置主要颜色 */
    font-size: 14px;
    /* 设置主要字号 */
    margin-right: 10px;
  }

  .label-subtext {
    color: #959FBA;
    /* 设置副文本颜色 */
    font-size: 14px;
    /* 设置副文本字号 */
  }
</style>
